﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

using FCNS.KeepMoney.Data;

namespace FCNS.KeepMoney.Configuration
{
    sealed class AppSerializer
    {
        public static AppConfigEx LoadConfig()
        {
            AppConfigEx tConfig = null;
            XmlSerializer xmlSerial = new XmlSerializer(typeof(AppConfigEx));

            FileStream fs = null;
            try
            {
                fs = new FileStream(AppDefines.appPath + "KeepMoney.config.xml", FileMode.Open,
                    FileAccess.Read, FileShare.Read);
                tConfig = (AppConfigEx)xmlSerial.Deserialize(fs);
                fs.Dispose();
            }
            catch (Exception) { tConfig = new AppConfigEx(); } // Do not assert
            fs = null;
            return tConfig;
        }

        public static bool SaveConfig(AppConfigEx appConfigEx)
        {
            XmlSerializer xmlSerial = new XmlSerializer(typeof(AppConfigEx));
            Stream fs = new FileStream(AppDefines.appPath + "KeepMoney.config.xml", FileMode.Create);

            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Encoding = new UTF8Encoding(false);
            xws.Indent = true;
            xws.IndentChars = "\t";

            XmlWriter xw = XmlWriter.Create(fs, xws);
            xmlSerial.Serialize(xw, appConfigEx);
            xw.Close();
            if (fs != null) { fs.Close(); fs = null; }
            return true;
        }
    }
}